from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.dialects.mysql import JSON
from sqlalchemy import Column, Integer, String, Date, DateTime, Text, ForeignKey
from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash

db = SQLAlchemy()

class User(db.Model):
    """用户表"""
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    password_hash = db.Column(db.String(128))
    created_at = db.Column(db.DateTime, default=datetime.utcnow)

    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)

class Elderly(db.Model):
    """老年人基本信息表"""
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50), nullable=False)
    gender = db.Column(db.String(10))
    birth_date = db.Column(db.Date)
    phone = db.Column(db.String(20))
    address = db.Column(db.String(200))
    emergency_contact = db.Column(db.String(50))
    emergency_phone = db.Column(db.String(20))
    created_at = db.Column(db.DateTime, default=datetime.utcnow)

class HealthRecord(db.Model):
    """健康记录表"""
    id = db.Column(db.Integer, primary_key=True)
    elderly_id = db.Column(db.Integer, db.ForeignKey('elderly.id'), nullable=False)
    record_type = db.Column(db.String(50))  # 体检报告/病史记录/日常监测
    record_date = db.Column(db.DateTime)
    description = db.Column(db.Text)
    indicators = db.Column(db.JSON)  # 存储健康指标
    doctor_advice = db.Column(db.Text)  # 医生建议
    health_status = db.Column(db.String(20))  # 健康评级
    created_at = db.Column(db.DateTime, default=datetime.utcnow)

    # 建立与老年人表的关联关系
    elderly = db.relationship('Elderly', backref=db.backref('health_records', lazy=True))

    def evaluate_health_status(self):
        """评估健康状况"""
        if not self.indicators:
            return "未评估"
        
        temp = self.indicators.get('temperature')
        bp = self.indicators.get('blood_pressure', {})
        systolic = bp.get('systolic')
        diastolic = bp.get('diastolic')
        
        # 计算各项指标的状态
        temp_status = self._evaluate_temperature(temp)
        bp_status = self._evaluate_blood_pressure(systolic, diastolic)
        
        # 综合评估
        statuses = [temp_status, bp_status]
        if all(s == "非常健康" for s in statuses):
            return "非常健康"
        elif all(s in ["非常健康", "良好"] for s in statuses):
            return "良好"
        elif any(s == "需要治疗" for s in statuses):
            return "需要治疗"
        else:
            return "及格"

    def _evaluate_temperature(self, temp):
        """评估体温状况"""
        if not temp:
            return "未测量"
        if 36.3 <= temp <= 37.0:
            return "非常健康"
        elif 36.0 <= temp < 36.3 or 37.0 < temp <= 37.2:
            return "良好"
        elif 35.8 <= temp < 36.0 or 37.2 < temp <= 37.5:
            return "及格"
        else:
            return "需要治疗"

    def _evaluate_blood_pressure(self, systolic, diastolic):
        """评估血压状况"""
        if not systolic or not diastolic:
            return "未测量"
        
        if 90 <= systolic <= 120 and 60 <= diastolic <= 80:
            return "非常健康"
        elif 120 < systolic <= 130 and 80 < diastolic <= 85:
            return "良好"
        elif 130 < systolic <= 140 and 85 < diastolic <= 90:
            return "及格"
        else:
            return "需要治疗"

class HealthAdvice(db.Model):
    """健康建议表"""
    id = db.Column(db.Integer, primary_key=True)
    elderly_id = db.Column(db.Integer, db.ForeignKey('elderly.id'))
    advice_type = db.Column(db.String(50))  # 改善建议/预防方案/生活指导
    content = db.Column(db.Text)
    health_status = db.Column(db.String(20))  # 关联的健康状态
    created_at = db.Column(db.DateTime, default=datetime.utcnow)

    @staticmethod
    def generate_advice(health_record):
        """根据健康记录生成建议"""
        advice_list = []
        
        # 获取指标数据
        indicators = health_record.indicators or {}
        temp = indicators.get('temperature')
        bp = indicators.get('blood_pressure', {})
        systolic = bp.get('systolic')
        diastolic = bp.get('diastolic')
        
        # 体温建议
        if temp:
            temp_advice = HealthAdvice._get_temperature_advice(temp)
            if temp_advice:
                advice_list.append({
                    'type': '体温建议',
                    'content': temp_advice
                })
        
        # 血压建议
        if systolic and diastolic:
            bp_advice = HealthAdvice._get_blood_pressure_advice(systolic, diastolic)
            if bp_advice:
                advice_list.append({
                    'type': '血压建议',
                    'content': bp_advice
                })
        
        # 生活方式建议
        lifestyle_advice = HealthAdvice._get_lifestyle_advice(health_record.health_status)
        if lifestyle_advice:
            advice_list.append({
                'type': '生活方式建议',
                'content': lifestyle_advice
            })
        
        return advice_list

    @staticmethod
    def _get_temperature_advice(temp):
        """生成体温相关建议"""
        if temp >= 37.5:
            return """1. 建议及时就医检查，排除感染等情况
2. 多休息，保持充足睡眠
3. 注意补充水分
4. 保持室内通风，穿着适宜"""
        elif temp <= 35.8:
            return """1. 注意保暖，适当增加衣物
2. 避免长时间待在寒冷环境
3. 可以喝些温热饮品
4. 如持续低温，建议就医检查"""
        return None

    @staticmethod
    def _get_blood_pressure_advice(systolic, diastolic):
        """生成血压相关建议"""
        if systolic >= 140 or diastolic >= 90:
            return """1. 建议定期监测血压，每天固定时间测量
2. 限制钠盐摄入，每日不超过6克
3. 保持规律运动，以散步、太极等缓和运动为主
4. 避免情绪激动，保持心情平和
5. 遵医嘱服用降压药物
6. 建议定期进行心血管检查"""
        elif systolic <= 90 or diastolic <= 60:
            return """1. 建议定期监测血压变化
2. 起床时动作要缓慢，避免体位性低血压
3. 适当增加盐分摄入
4. 保证充足睡眠和休息
5. 如感觉头晕乏力，及时就医"""
        return None

    @staticmethod
    def _get_lifestyle_advice(health_status):
        """生成生活方式建议"""
        if health_status == "需要治疗":
            return """1. 建议及时就医，遵医嘱治疗
2. 规律作息，保证充足睡眠
3. 合理饮食，清淡为主
4. 适度运动，不要剧烈运动
5. 保持心情愉悦，避免焦虑"""
        elif health_status == "及格":
            return """1. 加强健康监测，定期体检
2. 调整作息时间，保证7-8小时睡眠
3. 注意饮食均衡，多吃蔬果
4. 坚持适度运动，每天30分钟
5. 保持良好心态"""
        elif health_status == "良好":
            return """1. 继续保持良好的生活习惯
2. 坚持规律运动，如散步、太极拳等
3. 保持均衡饮食
4. 定期体检，预防疾病"""
        elif health_status == "非常健康":
            return """1. 继续保持当前的健康生活方式
2. 可以适当增加运动强度
3. 带动家人一起保持健康的生活习惯
4. 定期体检，预防保健"""
        return None